from extensions.WXBizMsgCrypt import *
from extensions.common.schema import *
from extensions.en_wechat import *
from rest_framework.views import APIView


def sava(data):
    '''
        1. 或签：找到当前步骤，判断里面状态为2的时间值个数，如果只有一个，则创建，否则不创建。
        2. 会签，寻找到当前步骤，如果在状态为2的时间值列表中，最大值为erp系统记录的用户最大时间，则创建
        3. 依次审批:同步骤2（会签）
    '''
    user_id = 'LiDong'
    step = 1
    approverattr = 2
    w = WechatPy()
    spno = data['xml']['approvalinfo']['spno']
    data = w.get_applyDetail(spno)
    sp_status = data['info']['sp_status']
    if sp_status in [4]:
        print('撤销了')
        return False

    sp_record = data['info']['sp_record']
    count = 1
    time_list = []
    all_time_list = []
    if approverattr == 1:
        for record in sp_record:
            details = record['details']
            for detail in details:
                if detail['sp_status'] == 2:
                    all_time_list.append(detail['sptime'])
                    if count == step:
                        time_list.append(detail['sptime'])
            count += 1

        if time_list and all_time_list and max(time_list) == max(all_time_list):
            return True
        else:
            return False
    elif approverattr == 2:
        # 或签或审批
        user_time = 0
        user_step_status = 0
        for record in sp_record:
            details = record['details']
            step_status = record['sp_status']
            for detail in details:
                userid = detail['approver']['userid']
                if detail['sp_status'] == 2:
                    all_time_list.append(detail['sptime'])
                    if count == step:
                        time_list.append(detail['sptime'])
                        # 如果没有指定用户，需要用该状态作为全部审批完成的状态
                        user_step_status = step_status
                        if user_id == userid:
                            user_time = detail['sptime']
            count += 1

        if all_time_list and time_list:
            if user_id:
                if user_time == max(all_time_list):
                    return True
                else:
                    return False
            else:
                if max(time_list) == max(all_time_list) and user_step_status == 2:
                    return True
                else:
                    return False
        else:
            return False
    else:
        return False

        # 只需要创建第一次提交的数据
        # if len(time_list) == 1:
        #     print('开始导入数据')
    # if approverattr in [2, 3]:
    #     # 遍历步数
    #     count = 1
    #     time_list = []
    #     user_time = 0
    #     # 遍历步数里每一个用户状态
    #     for record in sp_record:
    #         # 如果步数与第三方数据库记录一致，则遍历所有用户，得到时间值，如果时间值最大，则创建数据
    #         if count == step:
    #             details = record['details']
    #             for detail in details:
    #                 print(detail)
    #                 userid = detail['approver']['userid']
    #                 if detail['sp_status'] == 2:
    #                     # 得到步数里的所有时间值，用来与第三方数据库指定人的时间值作比较
    #                     time_list.append(detail['sptime'])
    #                     # 使用记录第三方数据库记录用户id，与企业微信id 比较，来得到该用户提交时间
    #                     if user_id == userid:
    #                         user_time = detail['sptime']
    #         count += 1
    #
    #     if time_list and max(time_list) == user_time:
    #         print(time_list)
    #         print(user_time)
    #         print('开始导入数据')
    #         return True
    # print('没有导入数据')
    # return False


class EnterpriseWechatApplyApiView(APIView):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.wxcpt = WXBizMsgCrypt(
            settings.EXTERPRISE_WECHAT['stoken'],
            settings.EXTERPRISE_WECHAT['sencodingaeskey'],
            settings.EXTERPRISE_WECHAT['cropid']
        )

    def post(self, request, *args, **kwargs):
        '''接收回调数据'''
        # 从请求中获取必要的参数
        query_params = self.request.query_params
        sReqMsgSig = query_params.get("msg_signature")
        sReqTimeStamp = query_params.get('timestamp')
        sReqNonce = query_params.get('nonce')
        sReqData = request.body

        # 使用 wxcpt 对数据进行解密
        ret, sMsg = self.wxcpt.DecryptMsg(sReqData, sReqMsgSig, sReqTimeStamp, sReqNonce)
        if (ret != 0):
            return Response(status=status.HTTP_400_BAD_REQUEST)
        element = ET.fromstring(sMsg)
        data = XMLParse.parse_xml_to_dict(element)
        print(data)
        sava(data)
        return Response(status=status.HTTP_200_OK)

    def get(self, request, *args, **kwargs):
        '''验证url是否可以回调'''
        # 从请求中获取必要的参数
        query_params = self.request.query_params
        msg_signature = query_params.get("msg_signature")
        timestamp = query_params.get('timestamp')
        nonce = query_params.get('nonce')
        echostr = query_params.get('echostr')

        try:
            # 使用 wxcpt 对 URL 进行验证
            ret, sEchoStr = self.wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
            sEcho = int(sEchoStr)
            if ret != 0:
                print("ERR: VerifyURL ret: " + str(ret))
        except Exception as e:
            logger.error(str(e))
            sEcho = None
        return Response(sEcho)
